package servlet;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import entity.User;
import service.IUserService;
import service.impl.UserServiceImpl;

@WebServlet(name = "rs", urlPatterns = {"/regist"})
public class RegistServlet extends HttpServlet {

    private IUserService us = new UserServiceImpl();


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接受数据
        request.setCharacterEncoding("utf-8");
//        String username = request.getParameter("un");//获取表单输入框的文字
//        String password = request.getParameter("pwd");
        //接受数据
        BufferedReader reader = request.getReader();
        String userstr = reader.readLine();
        User user1 = JSON.parseObject(userstr, User.class);


        String username = user1.getUsername();
        String password = user1.getPassword();
        String password2 = user1.getPwd2();
        response.setContentType("text/html;charset=UTF-8");
        System.out.println(password + username + password2);
        int result = us.regist(username, password, password2);
        System.out.println(result);
        switch (result) {
            case 0://注册成功（直接重定向到登录页面）
                response.getWriter().write("success");
                break;
            case 1://密码不一致
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write("注册失败，密码不一致");//一次性数据，保存到请求作用域
//		response.sendRedirect("regist_fail.jsp");//不能用重定向跳转
                //要用转发：
//                RequestDispatcher rd = request.getRequestDispatcher("regist_fail.jsp");//获取转发器
//                rd.forward(request, response);//进行转发
                break;
            case 2://用户名占用
                response.setContentType("text/html;charset=utf-8");

//                request.setAttribute("msg", "用户名已占用！");
//                request.getRequestDispatcher("regist_fail.jsp").forward(request, response);//转发（合并语句）
                response.getWriter().write("用户名已被占用");
                break;
            default:
        }


    }

}
